package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.config.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.mq.config.MqConst;
import com.atguigu.gmall.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author: 李旭
 * @Time: 11:12
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询秒杀列表
    @GetMapping("/list")
    public List<SeckillGoods> list() {

        return seckillGoodsService.list();
    }

    @GetMapping("/{skuId}")
    public SeckillGoods getSeckillGoods(@PathVariable Long skuId) {
        return seckillGoodsService.getSeckillGoods(skuId);
    }

    //立即抢购
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //校验是否开始抢购了 或是 库存 没有了
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        //时间限制
        //结论： 参数1大于参数2为false     参数1小于等于参数2为true
        Date curTime = new Date();
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();

        if (DateUtil.dateCompare(endTime, curTime)) {
            // 2)当前时间  当前时间大于等于结束时间  商品活动已经结束
            return Result.fail().message("商品活动已经结束");
        }
        if (!DateUtil.dateCompare(startTime, curTime)) {
            //1)当前时间  开始时间大于当前时间 商品活动还没有开始
            return Result.fail().message("商品活动还没有开始");
        }
        //库存限制
        if (seckillGoods.getStockCount() <= 0) {
            //3)库存小于等于0 商品已经售完
            return Result.fail().message("商品已经售完");
        }
        //4）成功 返回 200 返回一个抢购码
        // UUID
        //时间戳
        //MD5
        String encrypt = MD5.encrypt(userId + "w:e" + skuId);
        return Result.ok(encrypt);
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
//        秒杀微服务
        String userId = AuthContextHolder.getUserId(request);
//        1、校验抢购码
        String encrypt = MD5.encrypt(userId + "w:e" + skuId);
        if(!encrypt.equals(skuIdStr)){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//       2、库存：状态位
        String status = (String) CacheHelper.get(skuId.toString());
        if("0".equals(status)){
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);//售完了
        }
//        3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setSkuId(skuId);
        userRecode.setUserId(userId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
//        4、返回成功 200
        return Result.ok();
    }

    //查询秒杀结果  轮训3S
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        秒杀微服务
//        1、是否有订单
        Object seckillOrder = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if(null != seckillOrder){
            //下了订单了
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
//        2、是否有抢购资格
        Object seckillZiGe = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if(null != seckillZiGe){
            //抢购 成功了  有资格 了
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
        }
//        3、是否用户购买过
        Object seckillUser = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId);
        if(null != seckillUser){
            //来过了 只能证明抢购失败
            return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
        }
//        4、校验状态位
        Object state = CacheHelper.get(skuId.toString());
        if("0".equals(state)){
            //已售完了
            return Result.build(null,ResultCodeEnum.SECKILL_FINISH);
        }
        //5、排队中
        return Result.build(null,ResultCodeEnum.SECKILL_RUN);
    }
}
